package cn.kk.base.exception;

import cn.kk.base.model.Result;
import cn.kk.code.ErrorCodeEnum;
import com.alibaba.fastjson.JSON;
import feign.FeignException;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import java.net.BindException;

/**
 * @author kinoko
 */
@Slf4j
@RestControllerAdvice
@ResponseBody
public class BaseExceptionAdvice implements ExceptionAdvice {

    /**
     * JSON参数校验异常
     * @param e 异常
     * @return 错误信息
     */
    @Override
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        String errorMsg = objectError.getDefaultMessage();
        log.error("[错误参数异常]" + errorMsg, e);
        return Result.error(errorMsg, ErrorCodeEnum.USER_ERROR_A0400.getCode());
    }

    /**
     * form表单参数校验异常
     * @param e 异常
     * @return 错误信息
     */
    @Override
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> methodArgumentNotValidExceptionHandler(BindException e) {
        log.error("[form表单参数校验异常]" + e.getMessage(), e);
        return Result.error(ErrorCodeEnum.USER_ERROR_A0400);
    }

    /**
     * 单参数校验异常
     * @param e 异常
     * @return 错误信息
     */
    @Override
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> methodArgumentNotValidExceptionHandler(ConstraintViolationException e) {
        log.error("[单参数校验异常]" + e.getMessage(), e);
        return Result.error(ErrorCodeEnum.USER_ERROR_A0400);
    }

    /**
     * 非法参数异常
     * @param e 异常
     * @return 错误信息
     */
    @Override
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<Object> illegalArgumentExceptionHandler(IllegalArgumentException e) {
        log.error("[非法参数异常]" + e.getMessage(), e);
        return Result.error(ErrorCodeEnum.USER_ERROR_A0400);
    }

    /**
     * 参数缺失异常
     * @param e 异常
     * @return 错误信息
     */
    @Override
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Object> httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException e) {
        log.error("[参数缺失异常]" + e.getMessage(), e);
        return Result.error(ErrorCodeEnum.USER_ERROR_A0400);
    }

    /**
     * 重复键异常
     * @param e 异常
     * @return 错误信息
     */
    @Override
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DuplicateKeyException.class)
    public Result<Object> duplicateKeyExceptionHandler(DuplicateKeyException e) {
        log.error("[重复键异常]" + e.getMessage(), e);
        return Result.error(ErrorCodeEnum.SYSTEM_ERROR_B0322);
    }

    /**
     * 未找到处理器异常
     * @param e 异常
     * @return 错误信息
     */
    @Override
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Object> httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e) {
        log.error("[未找到处理器异常]" + e.getMessage(), e);
        return Result.error(ErrorCodeEnum.SERVICE_ERROR_C0113);
    }

    /**
     * 远程调用异常
     * @param e 异常
     * @return 错误信息
     */
    @Override
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(FeignException.class)
    public Result<Object> feignExceptionHandler(FeignException e) {
        log.error("[远程调用异常]{}", e.getMessage());
        // 获取响应体
        String body = e.contentUTF8();
        Result<Object> result = JSON.parseObject(body, Result.class);
        // 无法转化常规格式的先初始化再返回
        if (result == null || StringUtils.isBlank(result.getCode())) {
            return Result.error();
        }
        return result;
    }

    /**
     * 未知异常
     * @param e 未知异常
     * @return 错误信息
     */
    @Override
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<Object> exceptionHandler(Exception e) {
        // 未知异常打印异常链
        log.error("[未知异常]:" + e.getMessage(), e);
        return Result.error();
    }

}